package com.hokai.base.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hokai.base.common.ResultMessage;
import com.hokai.sysManage.bo.TPermissionEntiry;
import com.hokai.sysManage.bo.TRoleEntity;
import com.hokai.sysManage.bo.TUserEntity;
import com.hokai.sysManage.dao.TPermissionMapper;
import com.hokai.sysManage.vo.VMenusPermission;
import com.hokai.utils.Page;

/*
* @ClassName: LoginController  
* @Description: TODO(登录Controller)  
* @author LinYing  
* @date 2018年9月14日  
 */
@Controller
public class LoginController {

	// @Autowired
	// private TUserService tUserService;

	@Autowired
	private TPermissionMapper tPermissionMapper;

	@RequestMapping(value = "/loginUser")
	@ResponseBody
	public ResultMessage loginUser(String username, String password, HttpServletRequest request) {

		ResultMessage resultMessage = new ResultMessage();

		UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
		Subject currentUser = SecurityUtils.getSubject();
		try {
			// 完成登录
			currentUser.login(usernamePasswordToken); // 其实调用的是AuthorizingRealm实现类中的doGetAuthenticationInfo(token)方法

			// boolean isAdd = currentUser.isPermitted("add");
			// System.out.println("isAdd:"+isAdd);
			// boolean isUpdate = currentUser.isPermitted("update");
			// System.out.println("isUpdate:"+isUpdate);

		} catch (UnknownAccountException uae) {
			resultMessage.setCode(2);
			resultMessage.setMessage("用户名不正确");
			return resultMessage;
		} catch (IncorrectCredentialsException ice) {
			resultMessage.setCode(3);
			resultMessage.setMessage("密码不正确");
			return resultMessage;
		}

		// 验证是否登录成功
		if (currentUser.isAuthenticated()) {
			resultMessage.setCode(1);
			resultMessage.setMessage("登录成功");
			SecurityUtils.getSubject().getSession().setTimeout(1000 * 60 * 60);// 1000*60*60*24
		}

		return resultMessage;
	}

	@RequestMapping(value = "/logout")
	@ResponseBody
	public ResultMessage logout() {
		ResultMessage resultMessage=new ResultMessage();
		// 使用权限管理工具进行用户的退出，跳出登录，给出提示信息(会自动销毁session)
		SecurityUtils.getSubject().logout();
		resultMessage.setResult("1");
		resultMessage.setMessage("成功退出");
		System.out.println("成功退出");
		return resultMessage;
	}

	@RequestMapping(value = "/currUser")
	@ResponseBody
	public TUserEntity currUser() {
		TUserEntity userEntity = (TUserEntity) SecurityUtils.getSubject().getPrincipal();
		return userEntity;
	}

	@RequestMapping(value = "/currPermissions")
	@ResponseBody
	public Map<String, Object> currPermissions() {
		Map<String, Object> map = new HashMap<>();

		TUserEntity userEntity = (TUserEntity) SecurityUtils.getSubject().getPrincipal();
		List<TPermissionEntiry> permissionMenus = new ArrayList<>();
		boolean falgAdd = false;
		if(null != userEntity.getRoleEntities()) {
			for (TRoleEntity roleEntity : userEntity.getRoleEntities()) {
				if (roleEntity.getrType().equals("1")) {
					permissionMenus = roleEntity.getPermissionEntiries();
				}
				if (roleEntity.getrType().equals("3")) {
					for (TPermissionEntiry permissionEntiry : roleEntity.getPermissionEntiries()) {
						if (permissionEntiry.getName().equals("新增")) {
							falgAdd = true;
						}
					}

				}
			}
		}
		
		Page<TPermissionEntiry> page = new Page<>();
		page.addParam("type", "1");
		page.addParam("pnoIsNull", "true");
		List<TPermissionEntiry> firstMenus = tPermissionMapper.queryAllotPermissions(page);

		List<VMenusPermission> menusPermissions = new ArrayList<>();
		
		// 添加新增月报和周报
		if (falgAdd) {
			VMenusPermission menusPermission = new VMenusPermission();
			List<TPermissionEntiry> childrenPers = new ArrayList<>();
			menusPermission.setName("报告填写");
			menusPermission.setType(1);
			menusPermission.setUrl("");
			menusPermission.setClassName("el-icon-menu");
			TPermissionEntiry dayEntiry = new TPermissionEntiry();
			dayEntiry.setClassName("");
			dayEntiry.setIndex("2-1");
			dayEntiry.setName("日报填写");
			dayEntiry.setUrl("dayWork");
			dayEntiry.setType(1);
			childrenPers.add(dayEntiry);
			TPermissionEntiry weekEntiry = new TPermissionEntiry();
			weekEntiry.setClassName("");
			weekEntiry.setIndex("2-2");
			weekEntiry.setName("周报填写");
			weekEntiry.setUrl("weekWork");
			weekEntiry.setType(1);
			childrenPers.add(weekEntiry);
			menusPermission.setIndex("2");
			menusPermission.setChildrenPermissions(childrenPers);
			menusPermissions.add(menusPermission);
		}
		map.put("menus", menusPermissions);

		for (TPermissionEntiry firstMenu : firstMenus) {
			if (null == firstMenu.getPno() || firstMenu.getPno().equals("")) {// 一级菜单
				boolean flag = false;
				for (TPermissionEntiry permissionMenu : permissionMenus) {
					if (permissionMenu.getNo().equals(firstMenu.getNo())) {
						flag = true;
					}
				}
				if (flag) {
					List<TPermissionEntiry> childrenPermissions = new ArrayList<>();
					VMenusPermission menusPermission = new VMenusPermission();
					menusPermission.setId(firstMenu.getId());
					menusPermission.setName(firstMenu.getName());
					menusPermission.setType(1);
					menusPermission.setUrl(firstMenu.getUrl());
					menusPermission.setClassName(firstMenu.getClassName());
					menusPermission.setNo(firstMenu.getNo());
					menusPermission.setIndex(firstMenu.getIndex());
					for (TPermissionEntiry permissionMenu : permissionMenus) {
						if (permissionMenu.getNo().equals(firstMenu.getNo())) {
							childrenPermissions.add(permissionMenu);
						}
					}
					menusPermission.setChildrenPermissions(childrenPermissions);
					menusPermissions.add(menusPermission);
				}

			}
		}

		return map;
	}
	
	
	
	/**  
	* @Title: currCrudPermissions  
	* @Description: TODO(查看当前用户拥有的操作权限)  
	* @return Map<String,Object>    返回类型  
	*/  
	@RequestMapping(value = "/currCrudPermissions")
	@ResponseBody
	public List<String> currCrudPermissions() {
		TUserEntity userEntity = (TUserEntity) SecurityUtils.getSubject().getPrincipal();
		List<String> curdStrs=new ArrayList<>();
		List<TPermissionEntiry> permissionEntiries=new ArrayList<>();
		for (TRoleEntity tRoleEntity : userEntity.getRoleEntities()) {
			if(tRoleEntity.getrType().equals("3")) {// 1:菜单角色 2:数据角色 3:操作角色
				permissionEntiries = tRoleEntity.getPermissionEntiries();
				for (TPermissionEntiry tPermissionEntiry : permissionEntiries) {
					curdStrs.add(tPermissionEntiry.getName());
				}
			}
		}
		System.out.println("curdStrs.size:"+curdStrs.size());
		return curdStrs;
	}

}
